import { getImgPath } from '../assets'
import { Pages, hideLoading, relaunch, showModal, showToast } from '.'
import { useSystemInfo } from '@/store/system'
import { getLocationInfo, removeLocationInfo, setLocationInfo } from '@/store'
import { uniEvent } from '@/enums'

/**
 * 授权定位
 * @param {boolean} cancelback  取消授权时是否有回调值
 */
export const authLocation = async (cancelback = true, isShowModal = true) =>
  new Promise<UniApp.GetLocationSuccess>(async (resolve, reject) => {
    const { userLocation } = storeToRefs(useSystemInfo())
    uni.getSetting({
      withSubscriptions: true,
      success: async (conf) => {
        if (conf.authSetting['scope.userLocation']) {
          // 同意过定位授权
          const position = await locate()
          uni.$emit('sure_location', true)
          resolve(position)
        }
        else {
          userLocation.value = false
          if (isShowModal) { // 是否显示弹窗
            showModal({
              title: '获取位置时发生异常，您可点击小程序右上角-设置-允许获取位置',
              confirmText: '去设置',
              success: (res: { confirm: boolean }) => {
                if (res.confirm) {
                  uni.openSetting({
                    success: async (e) => {
                      console.log(e.authSetting['scope.userLocation'], 'e.authSetting[\'scope.userLocation\']')
                      if (e.authSetting['scope.userLocation']) {
                        const position = await locate()
                        resolve(position)
                      }
                      else {
                        reject(false)
                      }
                    },
                  })
                }
                else {
                  removeLocationInfo()
                  cancelback && uni.$emit('enable_location', false)
                  reject(false)
                }
              },
              fail: () => {
                reject(false)
              },
            })
          }
          else {
            reject(false)
          }
        }
      },
      fail: () => {
        uni.$emit('enable_location')
        reject(false)
      },
    })
  })

/** 是否展示地址 */

let showDistance = false
export const locate = () =>
  new Promise<UniApp.GetLocationSuccess & { timer?: number }>((_resolve, _reject) => {
    const { userLocation } = storeToRefs(useSystemInfo())
    const position = getLocationInfo()
    // 系统getLocation 30s 获取一次  这里延续到60s
    if (new Date().getTime() - position.timer < 1000 * 60) {
      setLocationInfo(position)
      _resolve(position as unknown as UniApp.GetLocationSuccess)
    }
    else {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          setLocationInfo({
            latitude: res.latitude,
            longitude: res.longitude,
            timer: new Date().getTime(),
          })

          console.log(res, 'location')
          userLocation.value = true
          showDistance = true
          _resolve(res)
        },
        fail: (res: UniApp.GetLocationSuccess & { errMsg: string }) => {
          console.log(res, 'location')
          if (res.errMsg.includes('getLocation:fail 频繁调用会增加电量损耗')) {
            if (!position.latitude)
              showDistance = false
          }
          else {
            showDistance = false
          }
          _resolve(position as unknown as UniApp.GetLocationSuccess)
        },
      })
    }
  })

/**
 * 获取订阅配置
 */
export const subscriptionsSetting = () =>
  new Promise<UniApp.GetLocationSuccess>(async () => {
    // const { subscriptionsConfig } = storeToRefs(useSystemInfo())
    uni.getSetting({
      withSubscriptions: true,
      success: async (conf) => {
        console.log(conf, 'wx config', conf.subscriptionsSetting.itemSettings)
        // if (conf.subscriptionsSetting.mainSwitch) {
        //   if (
        //     conf.subscriptionsSetting.itemSettings?.[tempsId] === 'accept'
        //   )
        //     subscriptionsConfig.value.sub = true
        //   if (
        //     conf.subscriptionsSetting.itemSettings?.[tempsId] === 'accept'
        //   )
        //     subscriptionsConfig.value.sub = true
        // }
      },
      fail: async () => { },
    })
  })

/**
 * 获取微信授权码
 */
export const getWxCode = async () =>
  new Promise<string>((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        if (res.errMsg === 'login:ok')
          resolve(res.code)
        else
          reject('wechat auth fail')
      },
      fail: () => {
        reject('wechat auth fail')
      },
    })
  })

/** 订阅消息 */
export const subscribeMessage = (tmplIds: string[]) =>
  new Promise((resolve) => {
    uni.requestSubscribeMessage({
      tmplIds,
      success: (res) => {
        console.log('消息订阅成功：', res)
      },
      fail: (err) => {
        console.log('消息订阅失败：', err)
      },
      complete: () => resolve(true),
    })
  })

export const defaultShare = () => {
  return {
    title: 'title~',
    imageUrl: getImgPath('sharecover.png'),
    path: '/pages/home/index',
  }
}
/**
 * 打开地图
 */
export const openMap = (store: {
  latitude?: string
  longitude?: string
  venueName?: string
  venueAddress?: string
}) => {
  uni.openLocation({
    latitude: +store.latitude!,
    longitude: +store.longitude!,
    name: store.venueName,
    address: store.venueAddress,
  })
}

/**
 * 打电话
 */
export const callMobile = (phoneNumber: string) => {
  showModal({
    title: '拨打电话',
    content: phoneNumber,
    confirmText: '呼叫',
    success: (res: { confirm: any }) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber,
        })
      }
    },
  })
}

export const resetLocaltion = async () => {
  if (showDistance) {
    const { longitude, latitude, timer = new Date().getTime() } = await locate()
    setLocationInfo({ latitude, longitude, timer })
  }
}

/**
 * 监听网络状态
 */
export const NetworkStatusChange = (cb?: Function) => {
  const tabberArr = [Pages.首页]
  const page = getCurrentPages()
  const route = page[page.length - 1]?.route ? `/${page[page.length - 1]?.route}` : ''
  const { isConnected } = storeToRefs(useSystemInfo())
  return new Promise<UniApp.GetNetworkTypeSuccess>((_resolve) => {
    uni.getNetworkType({ // 获取网络状态
      success(res) {
        if (isConnected.value && res.networkType !== 'none') {
          cb && cb()
        }
        else if (!isConnected.value && res.networkType !== 'none') {
          // 当前为断网状态 但是网络状态变更为连接 跳转首页
          isConnected.value = true
          // relaunch(Pages.首页)
          if (route && tabberArr.includes(route as Pages))
            relaunch(route as Pages)
          else
            relaunch(Pages.首页)
        }
        else if (isConnected.value && res.networkType === 'none') {
          uni.$emit(uniEvent.关闭Loading)
          isConnected.value = false
          // 当前为网络为连接状态 但是网络状态变更为断开 跳转失去网络页面
          hideLoading()
          showToast({
            title: '连接网络失败,请检查网络设置',
          })
          if (!route || !tabberArr.includes(route as Pages)) {
            setTimeout(() => {
              relaunch(Pages.失去网络)
            }, 500)
          }
          throw new Error('失去网络')
        }
        else if (!isConnected.value && res.networkType === 'none') {
          uni.$emit(uniEvent.关闭Loading)
          showToast({
            title: '连接网络失败,请检查网络设置',
          })
        }
      },
    })
  })
}
